package xyz.xiaoshengfu.bookstore.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import xyz.xiaoshengfu.bookstore.pojo.TbBook;
import xyz.xiaoshengfu.bookstore.service.IBookService;

@Controller
public class BookController {

	@Autowired
	IBookService bookService;

	@RequestMapping("/book_list")
	public String showBookList(String bookName, HttpServletRequest request) {
		long start = System.currentTimeMillis();
		List<TbBook> bookList = null;
		if (StringUtils.isNoneBlank(bookName)) {
			bookList = bookService.getTbBookListByName(bookName);
		} else {
			bookList = bookService.getTbBookList();
		}
		long end = System.currentTimeMillis();
		request.setAttribute("executionTime", end - start);
		request.setAttribute("bookName", bookName);
		request.setAttribute("bookList", bookList);
		return "book_list";
	}

	@RequestMapping("/book_edit")
	public String editBook(TbBook tbBook) {
		if (tbBook != null && tbBook.getId() != null) {
			tbBook.setIsDeleted(null);
			bookService.editTbBook(tbBook);
		}
		return "redirect:/book_list";
	}

	@RequestMapping("/book_del/{id}")
	public String delBook(@PathVariable Long id) {
		if (id != null) {
			bookService.delTbBookById(id);
		}
		return "redirect:/book_list";
	}

	@RequestMapping("/book_add")
	public String addBook(TbBook tbBook) {
		if (tbBook != null) {
			bookService.addTbBook(tbBook);
		}
		return "redirect:/book_list";
	}

}
